/*
 * Copyright 2015 The gRPC Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package top.todu.leaning.opentelemetry_loki.grpc.helloworld;

import static top.todu.leaning.opentelemetry_loki.grpc.helloworld.HelloWorldServer.PORT;

import io.grpc.Channel;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.StatusRuntimeException;
import io.grpc.examples.helloworld.GreeterGrpc;
import io.grpc.examples.helloworld.HelloReply;
import io.grpc.examples.helloworld.HelloRequest;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PreDestroy;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * A simple client that requests a greeting from the {@link HelloWorldServer}.
 */
@Slf4j
@Component
public class HelloWorldClient {

  private final ManagedChannel channel;
  private static final String target = "localhost:" + PORT;

  private final GreeterGrpc.GreeterBlockingStub blockingStub;

  public HelloWorldClient() {
    channel = ManagedChannelBuilder.forTarget(target)
        .usePlaintext()
        .build();

    blockingStub = GreeterGrpc.newBlockingStub(channel);
  }

  /** Say hello to server. */
  public String greet(String name) {
    log.info("Will try to greet " + name + " ...");
    HelloRequest request = HelloRequest.newBuilder().setName(name).build();
    HelloReply response;
    try {
      response = blockingStub.sayHello(request);
    } catch (StatusRuntimeException e) {
      log.error("RPC failed: "+e.getStatus(), e);
      return "error";
    }
    log.info("Greeting: " + response.getMessage());
    return response.getMessage();
  }


  @PreDestroy
  @SneakyThrows
  public void close() {
    channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS);

  }
}
